package com.qimen.task;

import com.qimen.bean.Qimen;
import com.qimen.controller.QimenController;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.xhtmlrenderer.swing.Java2DRenderer;
import org.xhtmlrenderer.util.FSImageWriter;
import java.awt.image.BufferedImage;
import java.io.*;
import freemarker.template.Configuration;

@Component
public class teskProcess {
    @Autowired
    private QimenController qimenController;
    /**
     * @Description: 将ftl文件转html文件
     * @param templateName  被填充的ftl文件
     * @return html数据
     * @throws IOException
     * @Author:
     * @Date: 15:07
     */
    public static String ftlToString(Qimen qimen, String templateName) throws IOException {
        String value = "";
        Configuration configuration = new Configuration();
        String filName = templateName;
        String encoding = "UTF-8";

        StringWriter out = new StringWriter();
        configuration.setDirectoryForTemplateLoading(new File("/www/wwwroot/"));
        Template template = configuration.getTemplate(filName,encoding);
        template.setEncoding(encoding);

        try {
            template.process( qimen, out);
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        out.flush();
        out.close();
        value = out.getBuffer().toString();
        return value;
    }

    /**
     * @Description: html转为图片
     * @param html  html数据
     * @param inputFileName html文件路径
     * @param widthImage  图片的宽
     * @param heightImage 图片的高
     * @return  生成图片的路径
     * @throws IOException
     * @Author:
     * @Date: 15:07
     */
    public static  void turnImage(String html,String inputFileName,String outputFileName
            ,int widthImage, int heightImage) throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream(inputFileName);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
        BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
        bufferedWriter.write(html);
        bufferedWriter.newLine();
        bufferedWriter.flush();
        outputStreamWriter.close();
        fileOutputStream.close();
        bufferedWriter.close();
        File f = new File(inputFileName);
        Java2DRenderer renderer = new Java2DRenderer(f, widthImage, heightImage);
        BufferedImage image = renderer.getImage();
        //存储图片
        FSImageWriter imageWriter = FSImageWriter.newJpegWriter(100f);
        imageWriter.write(image, outputFileName);
    }
}
